package com.example.common;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.exception.ServiceException;
import com.example.mapper.UserMapper;
import com.example.pojo.entity.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader("token"); //获取请求头header中的token
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token"); //url参数   ?token=xxx
        }
        //如果不是映射到方法的请求，直接放行
        if (handler instanceof HandlerMethod) {
            AuthAccess authAccess = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (authAccess != null) {
                return true;
            }

        }


        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401","请登录");
        }
        //获取token中的用户id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0); //JWT.decode(token) 解码jwt  token
        } catch (JWTDecodeException j) {
            throw new ServiceException("401","请登录");
        }

        //根据token中的userid查询数据库
        User user = userMapper.selectById(Integer.valueOf(userId));
        if (user == null) {
            throw new ServiceException("401","请登录");
        }

        //用户密码加密验证 token  通过用户密码加密之后生成一个验证器 jwtVerifier
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); //验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("401","请登录");
        }
        return true;
    }

}
